package com.skywalker.common.plugin.j2cache;

import com.jfinal.kit.LogKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.CacheObject;
import net.oschina.j2cache.J2Cache;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @user: skywalker
 * @date: 2019/4/13 9:21
 * @description: 借鉴了 小徐同学 / JFinal-vue-element-admin项目
 * https://gitee.com/xiaoxustudent/JFinal-vue-element-admin，并做了部分扩展
 */
public class J2CacheKit {

    private static CacheChannel cache;

    static void init(CacheChannel cache) {
        J2CacheKit.cache = cache;
    }

    static CacheChannel getOrAddCache() {
        if (cache == null) {
            synchronized (J2CacheKit.class) {
                cache = J2Cache.getChannel();
                if (cache == null) {
                    LogKit.error("J2Cache get Cache error, please check it");
                }
            }
        }
        return cache;
    }

    @SuppressWarnings("unchecked")
    public static <T> T get(String cacheName, Object key) {
        CacheObject cacheObject = getOrAddCache().get(cacheName, key.toString());
        return cacheObject != null ? (T) cacheObject.getValue() : null;
    }

    public static void put(String cacheName, Object key, Object value) {
        getOrAddCache().set(cacheName, key.toString(), (Serializable) value);
    }

    public static void remove(String cacheName, String... keys) {
        getOrAddCache().evict(cacheName, keys);
    }

    public static void removeAll(String cacheName) {
        getOrAddCache().clear(cacheName);
    }


    @SuppressWarnings("unchecked")
    public static <T> T get(String cacheName, Object key, IDataLoader dataLoader) {
        Object value = get(cacheName, key);
        if (value == null) {
            value = dataLoader.load();
            if (value != null) {
                put(cacheName, key, value);
            }
        }
        return (T) value;
    }


    public static Collection<String> getKeys(String cacheName) {
        Collection<String> keys = getOrAddCache().keys(cacheName);
        return keys == null ? new ArrayList<String>(keys) : null;
    }
}
